package com.ggk911.pharmacy_system.controller;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ggk911.pharmacy_system.entity.DTO.DrugInfoDTO;
import com.ggk911.pharmacy_system.entity.DTO.DrugPriceDTO;
import com.ggk911.pharmacy_system.entity.DrugInfo;
import com.ggk911.pharmacy_system.entity.DrugPrice;
import com.ggk911.pharmacy_system.service.impl.DrugInfoServiceImpl;
import com.ggk911.pharmacy_system.service.impl.DrugPriceServiceImpl;
import com.ggk911.pharmacy_system.service.impl.DrugSaleInfoServiceImpl;
import com.ggk911.pharmacy_system.util.RestResult;
import io.swagger.annotations.ApiParam;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

/**
 * 药品售价控制层
 *
 * @author ggk-911
 * @version 1.0 2023/4/11 17:29
 */

@RestController
@RequiredArgsConstructor
@Slf4j
@CrossOrigin
@RequestMapping("/drugPrice")
public class DrugPriceController {
    private final DrugPriceServiceImpl service;
    private final DrugInfoServiceImpl drugInfoService;


    //GET查询
    @GetMapping("/queryAll")
    public RestResult queryAll(@RequestParam(defaultValue = "1") Integer page,
                               @RequestParam(defaultValue = "10") Integer size) {
        Page<DrugPrice> drugPricePage = new Page<>(page, size);
        QueryWrapper<DrugPrice> wrapper = new QueryWrapper<>();

        service.page(drugPricePage, wrapper);

        return RestResult.ok("查询成功", drugPricePage);
    }

    //POST添加
    @PostMapping("/insert")
    public RestResult insert(DrugPrice drugPrice) {
        if (service.save(drugPrice)) {
            return RestResult.ok("添加成功");
        }
        return RestResult.error("添加失败");
    }

    //PUT修改
    @PutMapping("/update")
    public RestResult update(DrugPrice drugPrice) {
        if (service.updateByDrugInfoId(drugPrice)) {
            return RestResult.ok("修改成功");
        }
        return RestResult.error("修改失败");
    }

    //DELETE删除
    @DeleteMapping("/delete")
    public RestResult delete(Integer drugInfoId) {
        QueryWrapper<DrugPrice> wrapper = new QueryWrapper();
        wrapper.eq(drugInfoId != null, "drug_info_id", drugInfoId);

        if (service.remove(wrapper)) {
            return RestResult.ok("删除成功");
        }
        return RestResult.error("删除失败");
    }


    //GET获取所有数据集合listExcel
    @SneakyThrows
    @GetMapping("/listExcel")
    public void getListExcel(HttpServletResponse response) {

        List<DrugPrice> drugPriceList = service.listAd();
        List<DrugPriceDTO> drugPriceDTOList = new ArrayList<>();
        for (DrugPrice drugPrice : drugPriceList) {
            drugPriceDTOList.add(new DrugPriceDTO(drugPrice.getDrugInfo().getDrugInfoNationalCode(), drugPrice.getDrugPrice()));
        }
        drugPriceDTOList.forEach(System.out::println);

        //逻辑暂时放在controller

        // 设置响应头
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        // 设置防止中文名乱码
        String filename = URLEncoder.encode("价格列表", "utf-8");
        // 文件下载方式(附件下载还是在当前浏览器打开)
        response.setHeader("Content-disposition", "attachment;filename=" + filename + ".xls");

        // 生成excel
        ExportParams exportParams = new ExportParams();
        exportParams.setSheetName("药品价格");
        exportParams.setTitle("药品价格");
        Workbook sheets = ExcelExportUtil.exportExcel(exportParams, DrugPriceDTO.class, drugPriceDTOList);
        sheets.write(response.getOutputStream());
        sheets.close();
    }

    //POST表格导入
    @SneakyThrows
    @PostMapping("/importExcel")
    public RestResult importExcel(MultipartFile file) {

        //逻辑暂时放在controller
        if (file.isEmpty()) {
            throw new RuntimeException("上传文件为空");
        }
        ImportParams importParams = new ImportParams();
        importParams.setTitleRows(1);
        importParams.setHeadRows(1);
        InputStream inputStream = file.getInputStream();
        List<DrugPriceDTO> list = ExcelImportUtil.importExcel(inputStream, DrugPriceDTO.class, importParams);
        //拿到要导入的信息长度
        int size1 = list.size();
        inputStream.close();
        List<DrugPrice> drugPriceList = new ArrayList<>();
        list.forEach(item -> {
            //非空
            if (item.getDrugInfoNationalCode() != null && !"".equals(item.getDrugInfoNationalCode())) {
                if (item.getDrugPrice() != null && item.getDrugPrice() >= 0D) {
                    //查询到药品ID
                    DrugInfo drugInfo = drugInfoService.selectByDrugInfoNationalCode(item.getDrugInfoNationalCode());
                    System.out.println(drugInfo);
                    if (drugInfo != null) {
                        //拿到id
                        Integer drugInfoId = drugInfo.getDrugInfoId();
                        //添加到list
                        drugPriceList.add(new DrugPrice(drugInfoId, item.getDrugPrice(), null));
                    }
                }
            }
        });
        //筛选后的长度
        int size = drugPriceList.size();
        if (size == 0) return RestResult.error("表中无数据或数据重复");
        //这里要改成循环更新
        drugPriceList.forEach(item -> {
            service.update(item, new QueryWrapper<DrugPrice>().eq("drug_info_id", item.getDrugInfoId()));
        });
        return RestResult.ok("批量更新成功，总：" + size1 + ",成功导入：" + size);
    }
}
